<template>
  <div ref="containerRef">
    <slot></slot>
    <Teleport to="body">
      <div
        v-if="showMenu"
        class="context-menu"
        :style="{ left: x + 'px', top: y + 'px' }"
      >
        <div class="menu-list">
          <div
            @click="handleClick(item)"
            class="menu-item"
            v-for="item in menu"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup lang="ts">
import { useContextMenu } from '@/hooks/useContextMenu'

type MenuType = {
  label: string
}

defineProps({
  menu: {
    type: Array as () => MenuType[],
    default: () => []
  }
})

const emit = defineEmits(['select'])

const containerRef = ref<HTMLDivElement>()
const { x, y, showMenu } = useContextMenu(containerRef)

const handleClick = (item: MenuType) => {
  emit('select', item.label)
  showMenu.value = false
}
</script>

<style scoped lang="scss">
.context-menu {
  position: absolute;
  min-width: 100px;
  width: fit-content;
  background-color: #efefef;
  border-radius: 4px;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);
  padding: 10px;
  text-align: center;
  cursor: pointer;

  .menu-item {
    &:hover {
      background-color: #e0e0e0;
    }
  }
}
</style>
